package com.fzu.ess.sys.controller;

import com.fzu.ess.common.Const;
import com.fzu.ess.common.Model.JsonModel;
import com.fzu.ess.common.service.MailService;
import com.fzu.ess.sys.entity.User;
import com.fzu.ess.sys.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * Created by ercha on 2015/10/16.
 */
@Controller
public class ShiroController {

    @Autowired
    private UserService userService;

    @Autowired
    private MailService mailService;

    //首页
    @RequestMapping(value="/", method=RequestMethod.GET)
    public String homePage(){
        return "/jsp/common/home.jsp";
    }

    //登录
    @RequestMapping(value="/login*", method=RequestMethod.GET)
    public String loginPage(){
        return "/jsp/common/login.jsp";
    }

    @ResponseBody
    @RequestMapping(value="/login", method=RequestMethod.POST)
    public JsonModel login(String username, String password, Boolean rememberMe){
        //始终传入 username 进行身份验证，这样并发控制的也会比较简单
        if(username.contains("@")){
            User user = userService.findByEmail(username);
            if(user != null){
                username = user.getUsername();
            } else{
                return new JsonModel("用户名或密码错误!");
            }
        }
        return userService.login(username, password, rememberMe);
    }

    //登出,返回首页
    @RequestMapping(value="/logout", method = RequestMethod.GET)
    public String logout(){
        userService.logout();
        return "redirect:/";
    }

    //注册
    @RequestMapping(value="/register", method=RequestMethod.GET)
    public String registerPage(){
        return "/jsp/common/register.jsp";
    }


    @ResponseBody
    @RequestMapping(value="/register", method=RequestMethod.POST)
    public JsonModel register(User user){
        JsonModel jsonModel = userService.register(user);
        if(jsonModel.getSuccess()){
            //发送激活邮件
            mailService.sendActiveMail(user.getEmail());
//            if(null == mailService.sendActiveMail(user.getEmail())) {
//                jsonModel.setSuccess(false);
//                jsonModel.setMsg("发送激活邮件失败！");
//            }
//            } else{
//                jsonModel.setMsg("/registerSuccess?email=" + user.getEmail());
//            }
        }
        return jsonModel;
    }

    //已废弃
    @RequestMapping(value="/registerSuccess", method = RequestMethod.GET)
    public String registerSuccessPage(@RequestParam("email")String email, Model model){
        model.addAttribute("email", email);
        return "/jsp/recycle/registerSuccess.jsp";
    }

    @RequestMapping(value="/active", method = RequestMethod.GET)
    public String active(@RequestParam("uuid") String uuid, @RequestParam("code") String code, Model model){
        JsonModel jsonModel = userService.activeUser(uuid, code);

        model.addAttribute("success", jsonModel.getSuccess());
        model.addAttribute("msg", jsonModel.getMsg());
        return "/jsp/common/active.jsp";
    }

    @ResponseBody
    @RequestMapping(value="/sendActiveMail", method = RequestMethod.POST)
    public JsonModel sendActiveMail(String email){
        if(!email.contains("@")){
            User user = userService.findByUsername(email);
            if(user == null){
                return new JsonModel();
            }
            email = user.getEmail();
        }
        return mailService.sendActiveMail(email);
    }

    @RequestMapping(value="/kickOut", method=RequestMethod.GET)
    public String kickOutPage(){
        return "/jsp/common/kickOut.jsp";
    }

    @RequestMapping(value="/management", method = RequestMethod.GET)
    public String managementPage(){
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        User user = (User)session.getAttribute(Const.SESSION.USER);
        if(Const.USER_LEVEL.USER == user.getLevel()){
            return "/jsp/user/index.jsp";
        } else if(Const.USER_LEVEL.ADMIN == user.getLevel()){
            return "/jsp/admin/index.jsp";
        } else if(Const.USER_LEVEL.SUPER_ADMIN == user.getLevel()){
            return "/jsp/admin/index.jsp";
        } else{
            return "/jsp/common/home.jsp";
        }
    }

    @RequestMapping(value="/updatePassword", method=RequestMethod.GET)
    public String updatePasswordPage(){
        return "/jsp/common/updatePassword.jsp";
    }

    @ResponseBody
    @RequestMapping(value="/updatePassword", method=RequestMethod.POST)
    public JsonModel updatePassword(String oldPassword, String password){
        return userService.updatePassword(oldPassword, password);
    }

    @ResponseBody
    @RequestMapping(value="/confirmPassword", method=RequestMethod.POST)
    public boolean confirmPassword(String oldPassword){
//        System.out.println("password: " + oldPassword);
        try {
            return userService.confirmPassword(oldPassword);
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 忘记密码
     */
    @RequestMapping(value = "/forgetPassword", method = RequestMethod.GET)
    public String forgetPasswordPage(){
        return "/jsp/common/forgetPassword.jsp";
    }

    @ResponseBody
    @RequestMapping(value="/forgetPassword", method=RequestMethod.POST)
    public JsonModel forgetPassword(String email){
        return mailService.sendForgetPasswordMail(email);
    }

    @RequestMapping(value = "/resetPassword", method = RequestMethod.GET)
    public String resetPasswordPage(@RequestParam("uuid") String uuid, @RequestParam("code") String code, Model model){
        String email = mailService.hasMail(uuid, code);
        if(null != email){
            String password = userService.resetPassword(email);
            model.addAttribute("password", password);
            mailService.sendResetPasswordMail(email, password);
        } else {
            model.addAttribute("password", "");
        }
        return "/jsp/common/resetPassword.jsp";
    }

    //    @ResponseBody
//    @RequestMapping(value="/hasPrincipal", method=RequestMethod.GET)
//    public boolean hasPrincipal(String username, String email){
//        //System.out.println("username: " + username + "\nemail: " + email);
//        try {
//            if (username != null) return (userService.findByUsername(username) == null) ;
//            else return (userService.findByEmail(email) == null) ;
//        }catch(Exception e){
//            e.printStackTrace();
//            return false;
//        }
//    }
}
